package com.hfut.eeg.common.component;

import com.hfut.eeg.common.util.BlobListTrans;
import com.hfut.eeg.common.util.EEGLeadAlgorithm;
import com.hfut.eeg.dto.EEG;
import com.hfut.eeg.dto.EEGTrans;
import com.hfut.eeg.service.EEGGuideService;
import com.hfut.eeg.service.EEGService;
import com.hfut.eeg.socket.AiServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author 梁琦
 * @program: eeg
 * @Package com.hfut.eeg.common.component
 * @Description: 主要是对于数据库的操作，将EEG从数据库中获取并添加增量数据后返回
 * 为原型模式
 * @date 2019-11-23 21:33
 */
@Component("eegThread")
@Scope("prototype")
public class EEGThread implements Runnable{

    private static final Logger LOGGER = LoggerFactory.getLogger(EEGThread.class);
    //EEG数据库缓冲池的拷贝
    private ArrayList<ArrayList> cache;

    @Autowired
    private AiServer aiserver;

    @Autowired
    private EEGService eegService;

    @Autowired
    private EEGGuideService eegGuideService;

    @Autowired
    private EEGcache eeGcache;

    private EEG eeg;

    @Override
    public void run() {
        //插入EEG数据
        eegService.insertEEGData(new ArrayList<>(cache.subList(0,16)),eeGcache.getPatientId());
        String patientId = eeGcache.getPatientId();
        aiserver.setEegId(patientId);

        //准备插入单导数据
        if(insertSingleEEG(patientId)<1){
            LOGGER.error("插入单导数据错误");
        }

        //准备插入均导数据
        if(insertAllEEG(patientId)<1){
            LOGGER.error("插入均导数据错误");
        }
        //清除
        cache.clear();

    }

    /**
    * 插入单导数据的方法
    */
    private int insertSingleEEG(String eegId){
        ArrayList<ArrayList> singleGuide = EEGLeadAlgorithm.singleGuide(cache);
        if(cache==null ||singleGuide==null|| singleGuide.size()<16){
            LOGGER.error("EEGTHread insertSingleEEG error");
            return -1;
        }
        return eegGuideService.insertSingleGuide(singleGuide,eegId);
    }

    /**
    * 插入均导数据的方法
    */
    private int insertAllEEG(String eegId){
        ArrayList AllGuide = EEGLeadAlgorithm.alllGuide(cache);
        if(cache==null || AllGuide==null || AllGuide.size()<16){
            LOGGER.error("cache数据有误");
            return -1;
        }
        return eegGuideService.insertAllGuide(AllGuide,eegId);
    }


    public ArrayList<ArrayList> getCache() {
        return cache;
    }

    public void setCache(ArrayList<ArrayList> cache) {
        this.cache = cache;
    }

    public EEG getEeg() {
        return eeg;
    }

    public void setEeg(EEG eeg) {
        this.eeg = eeg;
    }

    public EEGcache getEeGcache() {
        return eeGcache;
    }

    public void setEeGcache(EEGcache eeGcache) {
        this.eeGcache = eeGcache;
    }
}
